package com.autonavi.yunda.yunji.common.exception;

import lombok.Getter;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * @author cswang
 * @date 2021/7/28 2:06 下午
 */

public class AmapException extends RuntimeException {

    @Getter
    private final AmapExceptionCode exceptionCode;
    @Getter
    private final String errorMessage;


    public AmapException(AmapExceptionCode exceptionCode) {
        super(exceptionCode.getText());
        this.exceptionCode = exceptionCode;
        this.errorMessage = exceptionCode.getText();
    }

    public AmapException(AmapExceptionCode exceptionCode, String message) {
        super(exceptionCode + ": " + message);
        this.exceptionCode = exceptionCode;
        this.errorMessage = message;
    }

    public AmapException(String errorMessage) {
        super(AmapExceptionCode.COMMON_SERVER_ERROR + ": " + errorMessage);
        this.exceptionCode = AmapExceptionCode.COMMON_SERVER_ERROR;
        this.errorMessage = errorMessage;
    }

    public AmapException(AmapExceptionCode exceptionCode, String message, Throwable cause) {
        super(message, cause);
        this.exceptionCode = exceptionCode;
        this.errorMessage = message;
    }

    public AmapException(AmapExceptionCode exceptionCode, Throwable cause) {
        super(cause);
        this.exceptionCode = exceptionCode;
        this.errorMessage = exceptionCode.getText();
    }

    public static AmapException wrap(Throwable e) {
        return wrap(e, AmapExceptionCode.COMMON_SERVER_ERROR);
    }

    public static AmapException wrap(Throwable e, AmapExceptionCode exceptionType) {
        if (e instanceof AmapException) {
            return (AmapException) e;
        } else if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
            return new AmapException(AmapExceptionCode.COMMON_THIRD_PARTY_TIMEOUT, e);
        } else {
            return new AmapException(exceptionType, e);
        }
    }
}
